<script setup lang="ts">
import { useNurseUser, use_hospital_dept_bed, useNurseInformation, useNurseSwiper, ChannelService } from '@/service';
import { ref, computed, reactive, onBeforeUnmount, onMounted } from 'vue';
import { useAuthStore, useAppStore } from '@/store';
import { useRouterPush } from '@/composables';
import { storeToRefs } from 'pinia';
import Taro, { hideLoading, showLoading, showToast, usePullDownRefresh, stopPullDownRefresh } from '@tarojs/taro';
import { useGetAuthInfo, useGlobal, useImage } from '@/hooks';
import { SUCCESS_MSG_DURATION } from '@/constants';
import { useDayjs, useEmitter } from '@/hooks/common';
import HealthCard from './healthCard.vue';
import Tabs from './new-tabs.vue';
import Info from './info.vue';
import Movie from './movie.vue';
import Countdown from './countdown.vue';
import Thumb from './thumb.vue';
import good from './good.vue';
import { calculateDistance, ChannelUtils, localStg } from '@/utils';
import { EventManager, EVENT_NAMES } from '@/utils/eventManager';
import LogoView from '@/components/logo-view.vue';
import PopularServices from '@/components/PopularServices.vue';
import RecommendView from '@/components/RecommendView.vue';
import ThreeLevelDirectory from '@/components/ThreeLevelDirectoryExample.vue';
import { useHospitalStore } from '@/store';
const hospitalStore = useHospitalStore();
// import { useNurseUser, use_hospital_dept_bed } from '@/service';
const emitter = useEmitter();

const { $dayjs } = useDayjs();

const { toHelp, toInformation, toNearShop } = useRouterPush();

// const { company } = storeToRefs(useNurseStore())
const { getHospitalListByArea, getConfig } = use_hospital_dept_bed();

const providerClass = computed(() => ' flex-col-center mt-4 w-360px  shadow  m_card  ');

const date = computed(() => (createTime: string) => {
  if (createTime) {
    const now = $dayjs();
    const date = $dayjs(createTime).from(now);
    return date;
  }
  return '';
});

const tabsRef = ref();
const myLocation = {latitude: 0, longitude: 0};
const myAddress = ref('');

// 腾讯地图API密钥
const TENCENT_MAP_KEY = "5UQBZ-3CUKW-WRURZ-3I4LN-7N6WK-ZGF75";
let isGuangxi = true;

// 将经纬度转换为地址
const reverseGeocode = (latitude: number, longitude: number) => {
  return new Promise<string>((resolve, reject) => {
    Taro.request({
      url: `https://apis.map.qq.com/ws/geocoder/v1/?location=${latitude},${longitude}&key=${TENCENT_MAP_KEY}`,
      success: (res: any) => {
        // reverseGeocode success
        if (res.data.status === 0) {
          const address = res.data.result.address;
          const formattedAddress = res.data.result.formatted_addresses?.recommend || address;
          const province = res.data.result.address_component.province;
          if(province.includes('广东')){
            isGuangxi = false;
          }
          resolve(formattedAddress);
        } else {
          reject(new Error('获取地址失败'));
        }
      },
      fail: (error: any) => {
        // reverseGeocode fail
        reject(error);
      }
    });
  });
};

onMounted(() => {
  Taro.getLocation({
        type: 'wgs84',
        needFullAccuracy: true,
        success(res) {
          // res getLocation地址获取
          myLocation.latitude = res.latitude;
          myLocation.longitude = res.longitude;
          
          // 将经纬度转换为地址
          reverseGeocode(res.latitude, res.longitude)
            .then((address: string) => {
              myAddress.value = address + (isGuangxi ? ' (广西)' : ' (广东)');
              // 当前地址
            })
            .catch((error) => {
              // 地址转换失败
              myAddress.value = '地址获取失败';
            })
            .finally(() => {
              getData();
            });
        },
        fail(error) {
          // 获取位置失败
          getData();
        }
    });
});

const { editDefaultHospital, getVisibleByHospital } = useNurseUser();

const { list } = useNurseInformation();

const { list: swiper_list } = useNurseSwiper();

const { nurseUser } = storeToRefs(useAuthStore());
const appStore = useAppStore();
const { setConfigVisible } = appStore;
const { configVisible } = storeToRefs(appStore);

// nurseUser

const { getHospitalList } = use_hospital_dept_bed();

useGlobal();

const swiperList = ref();

const informationList = ref();
const hospitalList = ref<any[]>([])

const logoPic = computed(()=>{
  const id = nurseUser.value.defaultHospital;
  // id
  let pic = ""
  hospitalList.value.forEach(item => {
    if(item.id === id) {
      pic = useImage(item.logo);
    }
  })
  // logoPic
  return pic
})

usePullDownRefresh(() => {
  getData();
  stopPullDownRefresh();
});

getData();
const curHospital = ref<any>(null);
async function getData() {
  showLoading({ title: '正在请求...' });

  const reulst = await list();

  if (!reulst.error && reulst.success) informationList.value = reulst.success;
  // informationList.value
  const { error, success } = await swiper_list();

  // console.log('轮播图 success', success);
  if (!error && success.records) swiperList.value = success.records;

  if (tabsRef.value) await tabsRef.value.getData();


  if(ChannelUtils.getShopId()){
    const result = await ChannelService.getHospitalListByChannel();
    hospitalList.value = result?.records || [];
    const item = hospitalList.value[0];
    curHospital.value = item;
    // distance.value = calculateDistance(myLocation.latitude, myLocation.longitude, item.latitude, item.longitude, 2)
    // nurseUser.value.defaultHospitalLatitude = item.latitude;
    // nurseUser.value.defaultHospitalLongitude = item.longitude;
    // localStg.set('defaultHospital', JSON.stringify(item));
    // Taro.setStorageSync('defaultHospital', JSON.stringify(curHospital.value));
    hospitalStore.setDefaultHospital(item);
    
    // 发送医院发生变化事件
    EventManager.emit(EVENT_NAMES.HOSPITAL_CHANGE, curHospital.value);
    EventManager.emit(EVENT_NAMES.SYS_ORG_CHANGE, {
        sysOrgCode: curHospital.value?.sysOrgCode,
        hospitalId: curHospital.value?.id,
        hospitalName: curHospital.value?.name
    });
  }
  else{
    // 根据获取的地址省份决定调用哪个城市的医院列表
    const cityName = isGuangxi ? "南宁市" : "广州市";
    const { error: err, success:suc } = await getHospitalListByArea(cityName);
    if (!err && suc) {
      hospitalList.value = suc
      changeDistance(suc)
    }
  }

  // if (Object.keys(configVisible.value).length === 0) {
    const newConfig: Record<string, boolean> = {};
    const res = await getVisibleByHospital(nurseUser.value.defaultHospital as string);
    // console.log('res === visible', res);
    // res 777
    const str = res?.success?.records?.[0]?.mods;
    if (str) {
        str.split(',').forEach((item: any) => {
            newConfig[item] = true;
        });
    }
    setConfigVisible(newConfig);

    // console.log('newConfig', newConfig, configVisible);
    // mods 888 from store
    // configVisible 999 from store
  // }

  hideLoading();
}
const distance = ref<number | string>(0)

function changeDistance(list: any) {
  // nurseUser.distance = distance;
  list.forEach((item: any) => {
    if(item.name === nurseUser.value.defaultHospitalName) {
      // changeDistance(item.children);
      distance.value = calculateDistance(myLocation.latitude, myLocation.longitude, item.latitude, item.longitude, 2)
      nurseUser.value.defaultHospitalLatitude = item.latitude;
      nurseUser.value.defaultHospitalLongitude = item.longitude;
      // localStg.set('defaultHospital', JSON.stringify(item));
      Taro.setStorageSync('defaultHospital', JSON.stringify(item));
      
      // 发送医院发生变化事件
      EventManager.emit(EVENT_NAMES.HOSPITAL_CHANGE, item);
      EventManager.emit(EVENT_NAMES.SYS_ORG_CHANGE, {
          sysOrgCode: item?.sysOrgCode,
          hospitalId: item?.id,
          hospitalName: item?.name
      });
    }
  })
}

const hospitalModule = reactive({
  show: false,
  showHospital: () => {
    hospitalModule.show = !hospitalModule.show;
  },
  save: async ({ defaultHospital, defaultHospitalName }: any) => {
    showLoading({ title: '正在保存...' });
    const defaultaddr = nurseUser.value.nurseUserAddrList;
    if (defaultaddr && defaultaddr.length > 0) {
      defaultaddr[0] = {
        ...defaultaddr[0],
        hospital: defaultHospital,
        hospitalName: defaultHospitalName,
        dept: '',
        deptName: '',
        bed: '',
        bedName: ''
      };
    }
    const { error } = await editDefaultHospital({ userId: nurseUser.value.id, defaultHospital, defaultHospitalName });
    hideLoading();
    if (!error) {
      showToast({
        title: '保存成功',
        icon: 'success',
        duration: SUCCESS_MSG_DURATION
      });
      useGetAuthInfo();
    }
  },
  onChange: (items: any) => {
    if (items.length == 0) return;
    const item = items[items.length - 1];
    hospitalModule.show = false;
    hospitalModule.save({ defaultHospital: item.key, defaultHospitalName: item.title });
  },
  lazyLoad: async (pid: string) => {
    const { error, success } = await getHospitalList(pid);
    if (!error && success?.length > 0) {
      const list = success?.map((item: any) => {
        return {
          value: item,
          text: item.title
        };
      });
      return list;
    }
    return [];
  }
});

const text = ref('欢迎使用');

// 搜索关键词
const keyword = ref('');

// 搜索服务
function searchService() {
  if (!keyword.value.trim()) {
    showToast({
      title: '请输入服务名称',
      icon: 'none',
      duration: 2000
    });
    return;
  }

  // 跳转到搜索结果页面
  Taro.navigateTo({
    url: `/pages/search-result/index?keyword=${keyword.value.trim()}`
  });
}

emitter.$on('select_hospital', () => {
  hospitalModule.show = true;
});

onBeforeUnmount(() => {
  emitter.$off('select_hospital');
});

// 切换医疗机构
function toNearShopNew() {
  // if(localStg.get('qudaoid')){
  //   Taro.showToast({
  //     title: '该渠道不支持切换机构',
  //     icon: 'none',
  //     duration: 1200
  //   });
  //   return
  // }
  Taro.navigateTo({
    url: '/package/nearshop/index',
    events: {
      switchNearShop(data: any) {
        getData(); // 切换城市后刷新机构
        stopPullDownRefresh();
      }
    }
  });
}

</script>

<template>
  <view class="w-375px text-primary flex-col-center mt-[var(--status-bar-height)] mt-30px">
    <!-- <view class="h-40px w-375px">
      <image class="w-full h-full" :src="logoPic" mode="aspectFit" />
    </view> -->
    <LogoView></LogoView>
    <!-- <view class="h-40px w-375px text-12px text-gray-400 text-center">{{ myAddress }}</view> -->

    <view class="h-60px w-375px">
      <view class="w-full h-full px-[18rpx] box-border flex items-center gap-[12rpx]">
        <!-- 机构名称区域 -->
        <view class="flex items-center gap-[8rpx] flex-shrink-0" @click="toNearShopNew()">
          <view class="i-local-location text-[28rpx] text-gray-500"></view>
          <text class="text-[28rpx] text-#334155 underline max-w-[240rpx] truncate">{{ hospitalStore.defaultHospital.name }}</text>
          <text class="text-[24rpx] text-gray-500">({{hospitalStore.distance}}km)</text>
        </view>
        <!-- 搜索区域 -->
        <view class="flex-1 flex ml-4 items-center relative bg-white pl-[24rpx] border border-solid border-gray-200 rounded-[40rpx] h-[48rpx] overflow-hidden shadow-sm">
          <input 
            type="text" 
            class="flex-1 bg-transparent px-[20rpx] pr-[48rpx] text-[#666]" 
            style="font-size: 24rpx;"
            v-model="keyword" 
            placeholder="请输入服务名称" 
            placeholder-class="text-gray-400"
            placeholder-style="font-size: 24rpx;"
            @confirm="searchService"
          />
          <view 
            class="absolute right-0 top-0 h-full w-[80rpx] z-10 flex items-center justify-center bg-#049669 transition-opacity"
            @tap="searchService"
          >
            <view class="i-local-search text-[32rpx] text-white"></view>
          </view>
        </view>
      </view>
    </view>


    <nut-noticebar class="w-full" :text="text" v-if="configVisible.broadcast"/>
    

    <view v-if="configVisible.swiper"
      class="w-375px flex-col-center justify-between items-center bg-white">

      <view class="w-375px">
        <!-- class="b-rounded-t-3" -->
        <nut-swiper class="w-375px" :init-page="0" :auto-play="3000" pagination-visible pagination-color="#059669"
          pagination-unselected-color="#808080">
          <nut-swiper-item v-for="(item, index) in swiperList" :key="index" class="w-375px swiper_item"
            @click="toInformation(item.toInformation)">
            <image :src="useImage(item.pic)" alt="" class="w-375px swiper_img" mode="aspectFit" draggable="false" />
          </nut-swiper-item>
        </nut-swiper>
      </view>
    </view>

   
      <view class="w-375px py-18rpx" v-show="configVisible.card">
        <view class="h-full flex-col-center px-10rpx">
          <HealthCard />
        </view>
      </view>

    <Info v-if="configVisible.info" />
    <Movie v-if="configVisible.video" />

    <!-- <PopularServices v-if="!configVisible.famous"/> -->
    <ThreeLevelDirectory v-if="configVisible.famous"/>
    <RecommendView v-if="configVisible.recommend"/>

    <Countdown v-if="configVisible.live" title="医疗专家直播" :target-timestamp="Date.now() + 1000 * 60 * 60 * 24 * 7" />
    <Countdown v-if="configVisible.team" title="护理服务团购" :target-timestamp="Date.now() + 1000 * 60 * 60 * 14 * 1" />
    <!-- <Thumb v-if="configVisible.thumb"></Thumb> -->


   
    <view class="w-375px">
      <view class="flex-col-center px-18rpx">
        <Tabs ref="tabsRef" :hospital="nurseUser?.defaultHospital || ''" />
      </view>
    </view>
  </view>
  <basic-hospital v-model:visible="hospitalModule.show" :lazy-load="hospitalModule.lazyLoad"
    :title="nurseUser.defaultHospitalName" @change="hospitalModule.onChange" />
  <view class="bg-primary w-96rpx h-96rpx flex-col-center b-rounded-1/2 pos-fixed pos-bottom-100px pos-right-10px"
    @click="toHelp">
    <view class="i-local-phone-sharp w-40rpx h-40rpx text-white" />
    <text class="text-white text-18rpx">客服台</text>
  </view>
</template>
<style lang="scss">
.m_card {
  backdrop-filter: blur(10px) brightness(90%);
  background-color: rgba(255, 255, 255, 0.7);
  border-radius: 10px;
}

.swiper_item {
  height: 372rpx;
}

.swiper_img {
  height: 100%;
  width: 100%;
}

._img {
  height: 100%;
  width: 100%;
  border-radius: 24rpx;
}

.iptx {
  border: solid 1px #999;
  border-radius: 30rpx;
  padding: 7rpx 20rpx;
}
.myx{
  font-size: 20rpx !important;
  border: solid 1px #ddd;
  padding: 4rpx 30rpx;
  border-radius: 30rpx;
}
</style>
